package com.xuexi.demos.service.impl;

import com.xuexi.demos.entity.DTO.UserDTO;
import com.xuexi.demos.entity.User;
import com.xuexi.demos.exception.PermissionException;
import com.xuexi.demos.mapper.UserMapper;
import com.xuexi.demos.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    /**
     *  注册用户
     * @param userDTO
     * @return
     */
    @Override
    public String Register(UserDTO userDTO) {
        if(userMapper.selectusername(userDTO.getUsername()))
        {
            //抛出异常
            throw new PermissionException("用户名已存在");
        }
        User user =new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setRandomCode(RandomCodeUtil.generate6DigitCode());
        user.setCreatedAt(LocalDateTime.now());
        user.setStatus(1);
        user.setUpdatedAt(LocalDateTime.now());
        return userMapper.insert(user) > 0 ? "注册成功" : "注册失败";
    }

    /**
     * 登录
     * @param username
     * @param password
     * @return
     */
    @Override
    public UserDTO login(String username, String password) {
        return userMapper.login(username, password);
    }

    /**
     * 更新用户状态
     * @param username
     * @param i
     */
    @Override
    public void updateStatus(String username, int i) {
        userMapper.updateStatus(username, i);
    }

    /**
     * 获取所有用户名
     * @return
     */
    @Override
    public List<String> getAllUsernames() {
        return userMapper.getAllUsernames();
    }

    /**
     * 获取所有在线用户
     * @return
     */
    @Override
    public List<String> getOnlineUsersFromDB() {
        return userMapper.getOnlineUsersFromDB();
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @Override
    public UserDTO getUserByUsername(String username) {
        return userMapper.getUserByUsername(username);
    }

    public class RandomCodeUtil {

        // 生成唯一的6位随机数字码（100000 ~ 999999）
        public static String generate6DigitCode() {
            return String.format("%06d", new Random().nextInt(900000) + 100000);
        }
    }
}
